{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import math\n",
    "import cv2\n",
    "from skimage.metrics import structural_similarity\n",
    "import imutils\n",
    "import os, sys\n",
    "import statistics \n",
    "import os\n",
    "from prettytable import PrettyTable\n",
    "import fnmatch\n",
    "from glob import glob\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def psnr(img1, img2):\n",
    "    mse = np.mean( (img1 - img2) ** 2 )\n",
    "    if mse == 0:\n",
    "        return 100\n",
    "    PIXEL_MAX = 255.0\n",
    "    return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ssim(im1,im2):\n",
    "    grayA = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)\n",
    "    grayB = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)\n",
    "    (score, diff) = structural_similarity(grayA, grayB, full=True)\n",
    "    return score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_progress(progress):\n",
    "    max_length=20\n",
    "    block = int(round(max_length*progress))\n",
    "    status=\" Done...\" if progress>=1 else \" \"\n",
    "    return ('Progress:[' + '=' * block +\n",
    "            ('>' if block < max_length else '') +\n",
    "            ' ' * (max_length - block) +\n",
    "            '] %.1f%%' % (progress * 100.)+status)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing Fold #1\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[KProgress:[====================] 100.0% Done..."
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing Fold #2\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[KProgress:[====================] 100.0% Done..."
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing Fold #3\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[KProgress:[====================] 100.0% Done..."
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing Fold #4\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[KProgress:[====================] 100.0% Done..."
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing Fold #5\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b[KProgress:[====================] 100.0% Done..."
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Calculation completed.\n"
     ]
    }
   ],
   "source": [
    "fold_ssim_mean=[]\n",
    "fold_psnr_mean=[]\n",
    "fold_ssim_stdev=[]\n",
    "fold_psnr_stdev=[]\n",
    "\n",
    "for fold_number in range(1,6):\n",
    "    inc = 0\n",
    "    files=[]\n",
    "    preds=[]\n",
    "    ground_truths=[]\n",
    "    psnrs=[]\n",
    "    ssims=[]\n",
    "    start_dir = os.getcwd() + \"./results/unet_256/test_latest/fold\"+str(fold_number)\n",
    "    patterns   = [\"*.png\", \"*.jpg\",\"*.jpeg\"]\n",
    "    for pattern in patterns:\n",
    "        for dir,_,_ in sorted(os.walk(start_dir)):\n",
    "            files.extend(glob(os.path.join(dir,pattern))) \n",
    "    print(\"Processing Fold #{}\".format(fold_number))\n",
    "    \n",
    "    for file in files:\n",
    "        if \"fake_B\" in file:\n",
    "            preds.append(file)\n",
    "        elif \"real_B\" in file:\n",
    "            ground_truths.append(file)\n",
    "\n",
    "    number_of_files=len(preds)\n",
    "    \n",
    "    for i in range(number_of_files):\n",
    "        gt=ground_truths[i]\n",
    "        pred=preds[i]\n",
    "        gt_name=gt[gt.rfind(\"/\")+1:]\n",
    "        pred_name=pred[pred.rfind(\"/\")+1:]\n",
    "        gt_image = cv2.imread(gt)\n",
    "        pred_image = cv2.imread(pred)\n",
    "        p=psnr(gt_image,pred_image)\n",
    "        s=ssim(gt_image,pred_image)\n",
    "        inc = inc + 1\n",
    "        sys.stderr.write('\\r\\033[K' + get_progress(inc/number_of_files))\n",
    "        #sys.stderr.flush()\n",
    "        psnrs.append(p)\n",
    "        ssims.append(s)\n",
    "           \n",
    "    fold_psnr_mean.append(statistics.mean(psnrs))\n",
    "    fold_ssim_mean.append(statistics.mean(ssims))\n",
    "    fold_psnr_stdev.append(statistics.stdev(psnrs))\n",
    "    fold_ssim_stdev.append(statistics.stdev(ssims))\n",
    "    time.sleep(.1)\n",
    "    sys.stderr.flush()\n",
    "print(\"\\nCalculation completed.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+----------------+-------+----------------+----------------+-----------------+-----------------+\n",
      "| Algorithm name | Fold# | PSNR Fold Mean | SSIM Fold Mean | PSNR Fold Stdev | SSIM Fold Stdev |\n",
      "+----------------+-------+----------------+----------------+-----------------+-----------------+\n",
      "|    EndoL2H     |   1   |    33.5233     |     0.7537     |      1.6796     |      0.1246     |\n",
      "|    EndoL2H     |   2   |    33.2080     |     0.7297     |      1.8028     |      0.1402     |\n",
      "|    EndoL2H     |   3   |    33.4158     |     0.7469     |      1.7047     |      0.1331     |\n",
      "|    EndoL2H     |   4   |    33.1877     |     0.7297     |      1.7187     |      0.1405     |\n",
      "|    EndoL2H     |   5   |    33.2504     |     0.7312     |      1.7577     |      0.1380     |\n",
      "+----------------+-------+----------------+----------------+-----------------+-----------------+\n",
      "\n",
      "+----------------+-----------+------------+-----------+------------+\n",
      "| Algorithm name | PSNR Mean | PSNR Stdev | SSIM Mean | SSIM Stdev |\n",
      "+----------------+-----------+------------+-----------+------------+\n",
      "|    EndoL2H     |  33.3170  |   0.0483   |   0.7382  |   0.0067   |\n",
      "+----------------+-----------+------------+-----------+------------+\n"
     ]
    }
   ],
   "source": [
    "x = PrettyTable()\n",
    "x.field_names = [\"Algorithm name\", \"Fold#\", \"PSNR Fold Mean\", \"SSIM Fold Mean\", \"PSNR Fold Stdev\", \"SSIM Fold Stdev\"]\n",
    "y = PrettyTable()\n",
    "y.field_names = [\"Algorithm name\", \"PSNR Mean\", \"PSNR Stdev\", \"SSIM Mean\", \"SSIM Stdev\"]\n",
    "\n",
    "algorithm=\"EndoL2H\"\n",
    "\n",
    "for i in range(len(fold_psnr_mean)):\n",
    "    x.add_row([algorithm, i+1, \"{:.4f}\".format(fold_psnr_mean[i]),\"{:.4f}\".format(fold_ssim_mean[i]), \"{:.4f}\".format(fold_psnr_stdev[i]), \"{:.4f}\".format(fold_ssim_stdev[i])])\n",
    "\n",
    "print(x)\n",
    "\n",
    "if len(fold_psnr_mean)>1:\n",
    "    y.add_row([algorithm, \"{:.4f}\".format(statistics.mean(fold_psnr_mean)), \"{:.4f}\".format(statistics.stdev(fold_psnr_stdev)), \"{:.4f}\".format(statistics.mean(fold_ssim_mean)), \"{:.4f}\".format(statistics.stdev(fold_ssim_stdev))])\n",
    "    print()\n",
    "    print(y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
